#include <ESP8266WiFi.h>
#include <MQTT.h>

#define RELAY_PIN 2

const char* ssid = "Wi-Fi SSID";      // Wi-Fi SSID
const char* password = "XXXXXXXX";    // Wi-Fi Password

// MQTT info
const char* hostname = "m14.cloudmqtt.com";
int port = 13536;
const char* user = "xxxx";
const char* user_password = "xxxx";
const char* id = "relay";

WiFiClient net;
MQTTClient client;

void connect() {
  Serial.print("checking wifi...");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }

  Serial.print("\nconnecting...");
  while (!client.connect(id, user, user_password)) {
    Serial.print(".");
    delay(1000);
  }

  Serial.println("\nconnected!");

  client.subscribe("/relay");
}

void messageReceived(String &topic, String &payload) {
  Serial.println("incoming: " + topic + " - " + payload);
  if (topic == "/relay") {
    if (payload == "on") {
      Serial.println("turn on relay");
      digitalWrite(RELAY_PIN, HIGH);
    } else {
      Serial.println("turn off relay");
      digitalWrite(RELAY_PIN, LOW);
    }
  }
}

void setup() {
  Serial.begin(115200);
  Serial.println("relay on mqtt message bus");

  pinMode(RELAY_PIN, OUTPUT);
  
  WiFi.begin(ssid, password);

  client.begin(hostname, port, net);
  client.onMessage(messageReceived);

  connect();
}

void loop() {
  client.loop();
  delay(10);  // <- fixes some issues with WiFi stability

  if (!client.connected()) {
    connect();
  }
}
